﻿using Ecommerce.DTO;
using Ecommerce.tbCommodity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Ecommerce
{
    public class Server : ApplicationService, Iserver
    {
        public IRepository<tbCommodityInfo, Guid> _repository;
        public readonly IRepository<CommodityImgurl, Guid> _commodityImgurls;
        public Server(IRepository<tbCommodityInfo, Guid> tbContexts,IRepository<CommodityImgurl, Guid> commodityImgurl)
        {
            _repository = tbContexts;
            _commodityImgurls = commodityImgurl;
        }
        public async Task<ImgurlDTO> Addimgurl(ImgurlsDTO imgurlsDTO)
        {
            var info = await _commodityImgurls.InsertAsync(ObjectMapper.Map<ImgurlsDTO, CommodityImgurl>(imgurlsDTO));
            return ObjectMapper.Map<CommodityImgurl, ImgurlDTO>(info);
        }

        [HttpPost]
        public async Task<tbCommodityInfoDto> CommodAdd(CreateUpdateCommodityInfoDto input)
        {
            var q = await _repository.InsertAsync(ObjectMapper.Map<CreateUpdateCommodityInfoDto, tbCommodityInfo>(input));
            return ObjectMapper.Map<tbCommodityInfo, tbCommodityInfoDto>(q);
        }

        [HttpGet]
        public List<tbCommodityInfoDto> tbContextList()
        {
            var list = _repository.ToList();
            return ObjectMapper.Map<List<tbCommodityInfo>, List<tbCommodityInfoDto>>(list);
        }
        [HttpPost]
        public string UploadFile(IFormFile File)
        {
            string rootdir = AppContext.BaseDirectory.Split(@"\bin\")[0];
            string fname = DateTime.Now.ToString("yyyyMMddHHmmssffff") + System.IO.Path.GetExtension(File.FileName);
            var path = rootdir + @"\Upload\" + fname;
            using (System.IO.FileStream fs = System.IO.File.Create(path))
            {
                File.CopyTo(fs);
                fs.Flush();//清空文件流
            }
            var newFileName= "http://localhost:8016/" + fname;//将能访问新文件的网址回传给前端
            return newFileName;
        }
    }
}
